Index
Overview


Unit testing is the most important part of software engineering.


That is where unit testing comes in. As coders, we let "test code" do the hard work of validating software. Otherwise, it's an effectively impossible (manual) task for complex problems.

Unit Tests Are the Key


Unit tests are the key to our success in coding.

This is Why:


Simple Definition


The essence of unit testing is this:


Test Case


A test case is simply a "case" (group) of tests.

For one case, we capture a given input condition.

For rectangle objects, we'll code two cases:

Test CaseDescription
RectangleTestCaseConstruct rectangle with inputs width=10 and height=5
RectangleEdgeTestCaseConstruct rectangle with no inputs (for this case, we expect defaults of width=0 and height=0)

Test case classes may be given any name (coder's choice).

Setting Up Input


There are different ways to setup input.

We'll look at a nice, simple (and suggested) approach.

beforeEach
We only need one setup method. It is called "beforeEach".

As you can see, we construct our test unit here and assign to the "unit" ivar.

Then, the "test methods" have access to this "unit" ivar.
beforeEach() {
	super.beforeEach();
	this.unit = new Rectangle(10, 5);
}


Test Methods (Testing Output)


Test methods can be given any name, but must begin with "test".

You will have a set of test methods in each test case class.

Our test examples will show a common test pattern. We assert that an actual result equals an expected result.

testGetArea
  • The first argument "50" is the expected result
  • The second argument "this.unit.getArea()" produces the actual result from the test unit object
testGetArea() {
	this.assertEquals(
1
50,
2
this.unit.getArea()); }
testGetPerimeter
  • The first argument "30" is the expected result
  • The second argument "this.unit.getPerimeter()" produces the actual result from the test unit object
testGetPerimeter() {
	this.assertEquals(
1
30,
2
this.unit.getPerimeter()); }


Step-By-Step Code Examples


We'll learn by example. We'll use a simple rectangle object to help with the learning curve.

First we'll get familiar with what we are testing:


And here are two test cases:


Here is the complete project source code for the examples.

Adding a Test Case


Adding tests to a test case is easy:


See the guide examples and sections above for more

Adding Tests


Adding tests to a test case is easy:


Test First


It might seem odd writing tests before solving a problem, but it has two advantages:


References